package com.example.controller;

import com.example.aspect.HttpAspect;
import com.example.domain.Bady;
import com.example.domain.Result;
import com.example.respository.BadyRepository;
import com.example.service.BadyService;
import com.example.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by 李强 on 2017/5/6.
 */
@RestController
public class BadyController {

    private  final static Logger logger= LoggerFactory.getLogger(BadyController.class);

   @Autowired
  private BadyRepository badyRepository;

   @Autowired
   private BadyService badyService;

   /*
     查询所有列表
    */

    @GetMapping(value = "/badys")
    public List<Bady> badyList(){

        logger.info("badyList");

     return badyRepository.findAll();

    }

    /*
    添加一个bady
    禁止age<18
    统一格式
     */

    @PostMapping(value = "/bady")
    public Result<Bady> badyAdd(@Valid Bady bady , BindingResult bindingResult){


        if(bindingResult.hasErrors()){

            return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
        }

        bady.setName(bady.getName());
        bady.setAge(bady.getAge());


        return ResultUtil.success(badyRepository.save(bady));

    }

    /*
    更新
     */
    @PutMapping(value = "/bad{id}")

    public Bady badyUpdate(@PathVariable("id") Integer id ,
                           @RequestParam("name") String name ,
                           @RequestParam("age") Integer age){

           Bady bady=new Bady();
           bady.setAge(age);
           bady.setName(name);
           bady.setId(id);
           return badyRepository.save(bady);
    }

    /*
    删除
     */
    @DeleteMapping(value = "/bad{id}")

    public void badyDelete(@PathVariable("id") Integer id ){
        badyRepository.delete(id);
    }

    /*
    通过Age查询
     */
    @GetMapping(value = "/bade/{age}")

    public List<Bady> badyListByAge(@PathVariable("age") Integer age){
       return badyRepository.findByAge(age);
    }

    /*
       插入数据
     */
    @PostMapping(value = "/brde/two")

    public void badyTwo(){
        badyService.inserTow();
    }


    @GetMapping(value = "/brde/throws/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception{
        badyService.getAge(id);


    }

}
